/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
(function($){
    $.fn.ajaxloading = function() {
        var obj = $(this).next();
        if(obj.attr('id') != 'ajaxloading') {
            var html = '<img id="ajaxloading" src="/images/ajax-loader.gif" alt="Loading.." />';
            $(this).after(html);
        }
        else {
            obj.remove();
        }
    };
    
})(jQuery);

;(function($){
    $.fn.subcontent = function (options) {
        var myoptions = {
            valuetofield: {},
            beforeShow:function(){ return true;},
            afterShow:function() {},
            url:'',
            data:'',
            createContainer:false
        };
        $.extend(myoptions, options);

        var container = $(this);
        if(myoptions.createContainer){
            $(this).append("<div id='subContainer'></div>");
            container = $(this).children('#subContainer');
        }
        var loadingDiv = '<div id="simplelogsubcontent_loading" align="center"><img src="/images/container-loader.gif" alt="Loading.." /></div>';
        if(!myoptions.beforeShow())
            return false;
        $.ajax({
            data:myoptions.data,
            beforeSend:function(){
                $(container).html(loadingDiv);
            },
            url:myoptions.url,
            success:function(data,status){
                $(container).html(data);
                myoptions.afterShow();
            },
            complete:function(){},
            global:false
        });
    };
})(jQuery);

;(function($){
    $.simplelogcontent = {

        mainContent: $('#content'),

        valuetofield:{},
        
        setFields:function() {
            $.extend(this.valuetofield,{});
            for(key in this.valuetofield) {
                $('#'+key).val(this.valuetofield[key]);
            }
        },

        beforeShow:function() {
            return true;
        },
        
        afterShow:function(containerID) {},
        
        show:function(urls) {
            if(!this.beforeShow())
                return;
            var constructor = this;
            var divamt = $(constructor.mainContent).children('div').length;
            urlarray = urls.split('/');
            g=0;
            for(var x=0;x<urlarray.length;x++) {
                if(urlarray[x] == 'index.php')
                    g = x+1;
            }
            var displayID = 'div#'+urlarray[g]+'_'+urlarray[g+1]+'_content';
             
            if($(constructor.mainContent).children(displayID).length>0) {
                $(constructor.mainContent).children('div').hide();
                $(constructor.mainContent).children(displayID).show();
                constructor.setFields();
                for(i=0;i<divamt;i++) {
                    if($(constructor.mainContent).children('div:eq('+i+')').attr('id')==displayID) {
                        $(constructor.mainContent).children('div:gt('+i+')').remove();
                        constructor.movetoBreadCrumbs(urls);
                        constructor.afterShow(displayID);
                        return;
                    }
                }
            }
            else {
                $.ajax({
                    url:urls,
                    complete:function() {
                        constructor.closeWaitingDialog();
                    },
                    success:function(data,status){
                        $(constructor.mainContent).children('div').hide();
                        $(constructor.mainContent).append(data);
                        constructor.addBreadCrumbs(urlarray[g]+'::'+urlarray[g+1],urls);
                        constructor.setFields();
                        constructor.afterShow(displayID);
                    },
                    global:false,
                    beforeSend:function(){
                        constructor.waitingDialog({
                            message:'Processing Request'
                        });
                    }
                });
            }
            
        },
        addBreadCrumbs: function(display,url) {
            $('.breadcrumbs').append(' &raquo; <a href="'+url+'">'+display+'</a>');
        },
        movetoBreadCrumbs:function(url){
            var totala = $('.breadcrumbs>a').length;
            var links = [];
            for(i=0;i<totala;i++) {
                links[i] = '<a href="'+$('.breadcrumbs>a:eq('+i+')').attr('href')+'">'+$('.breadcrumbs>a:eq('+i+')').html()+'</a>';
                if($('.breadcrumbs>a:eq('+i+')').attr('href')==url) {
                    i+=totala;
                }
            }
            $('.breadcrumbs').html(links.join(' &raquo; '));
        },

        backstepBreadCrumbs: function() {

    var totala = $('.breadcrumbs>a').length-2;
    return $('.breadcrumbs>a:eq('+totala+')').attr('href');
},

        waitingDialog: function(waiting) { // I choose to allow my loading screen dialog to be customizable, you don't have to
            if($("#loadingScreen").length <=0)
                $('body').append('<div style="display:none;" id="loadingScreen"></div>');

            $("#loadingScreen").html(waiting.message && '' != waiting.message ? waiting.message : 'Please wait...');
            $("#loadingScreen").dialog({
                autoOpen: false,	// set this to false so we can manually open it
                dialogClass: "loadingScreenWindow",
                closeOnEscape: false,
                draggable: false,
                width: 460,
                minHeight: 50,
                modal: true,
                buttons: {},
                resizable: false,
                open: function() {
                    // scrollbar fix for IE
                    $('body').css('overflow','hidden');
                },
                close: function() {
                    // reset overflow
                    $('body').css('overflow','auto');
                }
            });
            $("#loadingScreen").dialog('option', 'title', waiting.title && '' != waiting.title ? waiting.title : 'Loading');
            $("#loadingScreen").dialog('open');
        },
        closeWaitingDialog: function() {
            $("#loadingScreen").dialog('close');
        //$("#loadingScreen").dialog('destory');
        }

    };
})(jQuery);

;(function($){
    $.simplelogform = {
        formObj: $('form'),
    
        beforeSubmit:function() {
            return true;
        },
    
        Submit:function(formObj,params) {
            var constructor = this;
            if(typeof formObj != "undefined")
                $.simplelogform.formObj = formObj;
            //add new params
            $($.simplelogform.formObj).append("<div id='form_params'></div>");
            for(var key in params) {
                var input = "<input type='hidden' name='"+key+"' value='"+params[key]+"' />";
                $($.simplelogform.formObj).find("#form_params").append(input);
            }
            if($.simplelogform.beforeSubmit()) {
                $.ajax({
                    url:$($.simplelogform.formObj).attr('action'),
                    dataType:'json',
                    data:$($.simplelogform.formObj).serialize(),
                    type:'POST',
                    success:function(data,status){
                        if(data == '' || data == null){
                            constructor.afterSubmit(data);
                            return;
                        }
                        if(typeof data['attr'] != "undefined")
                            constructor.failValidation(data['attr'],data['summary']);
                        else if(typeof data['formerror'] != "undefined") {
                            confirmBox({
                                title:'Saving Error!',
                                msg:'Please contact admin'
                            });
                        }
                        else {
                            constructor.afterSubmit(data);
                        }
                    },
                    global:false,
                    error:function (XMLHttpRequest, textStatus, errorThrown) {
                        confirmBox({
                            title:"Form Error",
                            msg:"An error has occur. Please refresh or call the admin for assitance."
                        });
                    },
                    complete:function () {
                        closeWaitingDialog();
                    },
                    beforeSend:function(){
                        $(formObj).find('input, textarea').removeClass('error');
                        $(formObj).find('#errorsummary').empty();
                        waitingDialog({
                            message:'Validating and Saving form....'
                        });
                    }
                });
            }
            $($.simplelogform.formObj).find("#form_params").remove();
        },

        afterSubmit:function(data) {
            $.simplelogcontent.show($.simplelogcontent.backstepBreadCrumbs());
        },

        failValidation:function(Obj,Summary){
            for(i=0;i<Obj.length;i++){
                $(this.formObj).find('[name="'+Obj[i]+'"]').addClass('error');
            }
            $('#errorsummary').html(Summary);
        }
    };
})(jQuery);